from itsdangerous import TimedJSONWebSignatureSerializer as TJSSerializer, BadData
from django.conf import settings

def generate_save_user_token(open_id):
    """
    使用itsdangerous对原始的openid进行签名
    :param open_id: 原始的openid
    :return: 签名后的openid
    """
    serializer = TJSSerializer(settings.SECRET_KEY, 600)
    data = {
        "openid": open_id,
    }
    token = serializer.dumps(data)
    return token.decode()

def check_save_user_token(access_token):
    '''
    将access_token还原为openid
    :param access_token: 签名后的openid
    :return: 原始的openid
    '''
    try:
        serializer = TJSSerializer(settings.SECRET_KEY, 600)
        data = serializer.loads(access_token)
    except BadData:
        return None
    else:
        openid = data.get("openid")
        return openid


